package com.dtflys.easyel.compile;

import com.dtflys.easyel.exception.EasyElException;


import java.io.*;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;

/**
 * @author gongjun[jun.gong@thebeastshop.com]
 * @since v1.0.0
 */
public class EasyElSource {

    public final static int SOURCE_TEXT = 0x01;
    public final static int SOURCE_FILE = 0x02;

    private InputStream inputStream;
    private String sourceText;
    private int sourceType;
    private String sourceName;
    private final boolean isScript;

    private static Charset UTF8 = Charset.forName("UTF-8");


    public EasyElSource(String text, String sourceName) {
        this(true, new ByteArrayInputStream(text.getBytes(UTF8)), SOURCE_TEXT, sourceName);
        this.sourceText = text;
    }

    public EasyElSource(File file) throws FileNotFoundException {
        this(false, new FileInputStream(file), SOURCE_FILE, file.getAbsolutePath());
    }

    public EasyElSource(boolean isScript, InputStream inputStream, int sourceType, String sourceName) {
        this.inputStream = inputStream;
        this.sourceType = sourceType;
        this.sourceName = sourceName;
        this.isScript = isScript;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public int getSourceType() {
        return sourceType;
    }

    public String getSourceName() {
        return sourceName;
    }

    public List<EasyElSourceLine> getLineList(int startLine, int endLine) {
        BufferedReader reader = new BufferedReader(new StringReader(sourceText));
        int lineNum = 1;
        List<EasyElSourceLine> lineList = new LinkedList<>();
        for (; ; ) {
            try {
                String line = reader.readLine();
                if (line == null) {
                    break;
                }
                if (lineNum >= startLine && lineNum <= endLine) {
                    lineList.add(new EasyElSourceLine(lineNum, line));
                }
                lineNum++;
            } catch (IOException e) {
                throw new EasyElException("Failed read source at line " + lineNum);
            }
        }
        return lineList;
    }

    public List<EasyElSourceLine> getLineList(EasyElSourcePosition position) {
        return getLineList(position.getStartLine(), position.getEndLine());
    }

    public boolean isScript() {
        return isScript;
    }
}
